package admin

import (
	"context"
	"ia/apps/admin/dto/oin"
	ooutadmin "ia/apps/admin/dto/oout/admin"
	"ia/apps/admin/repository/query"
	modeladmin "ia/common/model/admin"
	"ia/common/storage"

	"gorm.io/gorm"
)

type AdminOrgService interface {
	Create(modeladmin.AdminOrg) error
	Edit(modeladmin.AdminOrg) error
	DeleteByIdList([]int64) error
	GetTable(oin.VxeTableIn) ([]*ooutadmin.AdminOrgOut, int64, error)
	GetList() ([]*ooutadmin.AdminOrgOut, error)
}

func NewAdminOrgService() *adminOrgService {
	return &adminOrgService{}
}

type adminOrgService struct{}

func (impl *adminOrgService) Create(in modeladmin.AdminOrg) (err error) {
	err = storage.GDB1.Create(&in).Error
	return
}

func (impl *adminOrgService) Edit(in modeladmin.AdminOrg) (err error) {
	err = storage.GDB1.Save(&in).Error
	return
}

func (impl *adminOrgService) DeleteByIdList(idList []int64) (err error) {
	err = storage.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&modeladmin.AdminOrg{}, "id in ?", idList).Error; err != nil {
			return err
		}
		return nil
	})
	return
}

func (impl *adminOrgService) GetTable(in oin.VxeTableIn) (rows []*ooutadmin.AdminOrgOut, total int64, err error) {
	m := query.Use(storage.GDB1).AdminOrgOut
	do := m.WithContext(context.Background())

	rows, total, err = do.FindByPage(in.Offset(), in.PageSize)
	return
}

func (impl *adminOrgService) GetList() (rows []*ooutadmin.AdminOrgOut, err error) {
	m := query.Use(storage.GDB1).AdminOrgOut
	do := m.WithContext(context.Background())

	rows, err = do.Find()
	return
}
